// 本地存储工具
const STORAGE_KEY = 'movie_websites';
const VERSION_KEY = 'movie_websites_version';
const CURRENT_VERSION = '1.6'; // 强制重置数据，确保使用最新的默认网站列表

// 默认示例数据
const defaultWebsites = [
  {
    id: '3',
    name: '低端影视2',
    url: 'https://ddys.pro/',
    searchUrl: 'https://ddys.pro/?s={keyword}&post_type=post',
    icon: 'https://ddys.pro/favicon.ico',
    disabled: false
  },
  {
    id: '8',
    name: '哒哒影视',
    url: 'https://dddym.com/',
    searchUrl: 'https://dddym.com/search?s={keyword}&p=1',
    icon: 'https://oss.jujihe.com/pm/dddym/code/1.0.23/image/favicon.svg',
    disabled: false
  },
  {
    id: '1753858562372',
    name: '毒舌电影',
    url: 'https://www.dushe9.app/',
    searchUrl: 'https://www.dushe9.app/search?k={keyword}&t=vVe%2B7zZjvWLTWI3g2QyrVg%3D%3D',
    icon: 'https://www.dushe9.app/favicon.ico',
    disabled: false
  },
  {
    id: '9',
    name: '饺子点播',
    url: 'https://www.jzvod.cc/',
    searchUrl: 'https://www.jzvod.cc/vodsearch/-------------.html?wd={keyword}',
    icon: 'https://www.jzvod.cc/statics/img/favicon.ico',
    disabled: false
  },
  {
    id: '10',
    name: 'Hdmoli',
    url: 'https://www.hdmoli.pro/',
    searchUrl: 'https://www.hdmoli.pro/search.php?searchkey={keyword}&submit=',
    icon: 'https://www.hdmoli.pro/favicon.ico',
    disabled: false
  },
  {
    id: '6',
    name: '豆瓣电影',
    url: 'https://movie.douban.com',
    searchUrl: 'https://movie.douban.com/subject_search?search_text={keyword}',
    icon: 'https://img3.doubanio.com/favicon.ico',
    disabled: false
  },
  {
    id: '2',
    name: 'libvio影视',
    url: 'https://www.libvio.site/',
    searchUrl: 'https://www.libvio.site/search/-------------.html?wd={keyword}&submit=',
    icon: 'https://www.libvio.site/statics/img/favicon.ico',
    disabled: false
  },
  {
    id: '1753858109753',
    name: '老地方影视',
    url: 'https://www.laodifang.tv',
    searchUrl: 'https://www.laodifang.tv/vodsearch/-------------.html?wd={keyword}&submit=',
    icon: 'https://www.laodifang.tv/template/conch/asset/img/play.svg',
    disabled: false
  },
  {
    id: '1753858230405',
    name: '光影迷',
    url: 'https://www.guangyingmi.com',
    searchUrl: 'https://www.guangyingmi.com/search-{keyword}-------------.html',
    icon: 'https://www.guangyingmi.com/template/mizhiady/statics/images/icon.png',
    disabled: false
  },
  {
    id: '1753858364360',
    name: '追剧兔',
    url: 'https://www.stslight.com/',
    searchUrl: 'https://www.stslight.com/vodsearch/-------------/?wd={keyword}',
    icon: 'https://www.stslight.com/',
    disabled: false
  },
  {
    id: '1753861340820',
    name: '红果短剧',
    url: 'https://www.hgdj.app/',
    searchUrl: 'https://www.hgdj.app/vodsearch/-------------.html?wd={keyword}&submit=',
    icon: 'https://www.hgdj.app/upload/site/20241004-1/2dbb4fd27405f07a49041063867c37f6.png',
    disabled: false
  },
  {
    id: '1753858686571',
    name: '捣蛋兔',
    url: 'https://www.dandantu.cc/',
    searchUrl: 'https://www.dandantu.cc/vodsearch/-------------.html?wd={keyword}',
    icon: 'https://www.dandantu.cc/mxtheme/images/favicon.png',
    disabled: false
  },
  {
    id: '1753856874293',
    name: '蜜桃影视',
    url: 'https://www.mtvod.cc',
    searchUrl: 'https://www.mtvod.cc/vodsearch.html?wd={keyword}',
    icon: 'https://img10.360buyimg.com/ling/jfs/t1/296685/31/18277/63972/685b007fF768b986b/79dd8580f8e23cec.png',
    disabled: false
  },
  {
    id: '1753858138987',
    name: '麦田影院',
    url: 'https://www.mtyy4.com/',
    searchUrl: 'https://www.mtyy4.com/vodsearch/-------------.html?wd={keyword}',
    icon: 'https://www.mtyy4.com/static/ds6/img/desklogo.png',
    disabled: false
  },
  {
    id: '4',
    name: 'gimy剧迷',
    url: 'https://gimy.ai/',
    searchUrl: 'https://gimy.ai/search/-------------.html?wd={keyword}',
    icon: 'https://gimy.ai/favicon.ico',
    disabled: false
  },
  {
    id: '5',
    name: 'Anime动漫',
    url: 'https://anime1.me',
    searchUrl: 'https://anime1.me/?s={keyword}',
    icon: 'https://anime1.me/favicon.ico',
    disabled: false
  },
  {
    id: '7',
    name: 'IMDb',
    url: 'https://www.imdb.com',
    searchUrl: 'https://www.imdb.com/find?q={keyword}',
    icon: 'https://m.media-amazon.com/images/G/01/imdb/images/favicon-2165806970._CB470047330_.ico',
    disabled: true
  },
  {
    id: '1',
    name: '素白白影视',
    url: 'https://www.subaibai.com',
    searchUrl: 'https://www.subaibai.com/search?q={keyword}',
    icon: 'https://www.subaibai.com/favicon.ico',
    disabled: true
  }
];

export const saveWebsites = (websites) => {
  try {
    console.log('=== saveWebsites 调试信息 ===');
    console.log('准备保存的数据:', websites);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(websites));
    console.log('数据已保存到localStorage');

    // 验证保存是否成功
    const saved = localStorage.getItem(STORAGE_KEY);
    console.log('验证保存结果:', saved);
  } catch (error) {
    console.error('保存网站数据失败:', error);
  }
};

// 清除所有存储数据的函数
export const clearAllData = () => {
  localStorage.removeItem(STORAGE_KEY);
  localStorage.removeItem(VERSION_KEY);
  console.log('已清除所有存储数据');
};

// 强制重置为默认数据
export const resetToDefaultData = () => {
  console.log('=== 强制重置为默认数据 ===');
  localStorage.removeItem(STORAGE_KEY);
  localStorage.removeItem(VERSION_KEY);
  localStorage.setItem(VERSION_KEY, CURRENT_VERSION);
  saveWebsites(defaultWebsites);
  console.log('已重置为默认数据:', defaultWebsites);
  return defaultWebsites;
};

// 测试localStorage读写的函数
export const testLocalStorage = () => {
  console.log('=== localStorage 测试 ===');

  // 检查当前存储的数据
  const currentVersion = localStorage.getItem(VERSION_KEY);
  const currentData = localStorage.getItem(STORAGE_KEY);
  
  console.log('当前版本:', currentVersion);
  console.log('期望版本:', CURRENT_VERSION);
  console.log('版本匹配:', currentVersion === CURRENT_VERSION);
  console.log('当前存储的网站数据长度:', currentData ? JSON.parse(currentData).length : 0);
  console.log('默认数据长度:', defaultWebsites.length);
  
  if (currentVersion !== CURRENT_VERSION) {
    console.log('版本不匹配，应该会重置为默认数据');
  }
  
  // 测试写入
  const testData = [{ id: 'test', name: 'Test Website' }];
  localStorage.setItem('test_key', JSON.stringify(testData));
  console.log('测试数据已写入');

  // 测试读取
  const readData = localStorage.getItem('test_key');
  console.log('读取的测试数据:', readData);
  console.log('解析后的数据:', JSON.parse(readData));

  // 清理测试数据
  localStorage.removeItem('test_key');
  console.log('测试数据已清理');
};

// 生成更新storage.js文件的代码
export const generateStorageUpdateCode = (websites) => {
  // 转义字符串中的特殊字符
  const escapeString = (str) => {
    if (!str) return '';
    return str.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n').replace(/\r/g, '\\r');
  };

  const websitesCode = websites.map(website => {
    return `  {
    id: '${escapeString(website.id)}',
    name: '${escapeString(website.name)}',
    url: '${escapeString(website.url)}',
    searchUrl: '${escapeString(website.searchUrl)}',
    icon: '${escapeString(website.icon)}',
    disabled: ${website.disabled || false}
  }`;
  }).join(',\n');

  return `// 默认示例数据
const defaultWebsites = [
${websitesCode}
];`;
};

// 导出当前网站列表为可复制的代码
export const exportWebsitesToCode = (websites) => {
  const code = generateStorageUpdateCode(websites);
  console.log('=== 生成的storage.js更新代码 ===');
  console.log(code);
  return code;
};

// 下载代码文件
export const downloadCodeFile = (websites, filename = 'defaultWebsites.js') => {
  const code = generateStorageUpdateCode(websites);
  const blob = new Blob([code], { type: 'text/javascript' });
  const url = URL.createObjectURL(blob);
  
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

export const loadWebsites = () => {
  try {
    const storedVersion = localStorage.getItem(VERSION_KEY);
    const stored = localStorage.getItem(STORAGE_KEY);

    console.log('=== loadWebsites 调试信息 ===');
    console.log('当前版本:', CURRENT_VERSION);
    console.log('存储的版本:', storedVersion);
    console.log('存储的数据:', stored);

    // 如果版本不匹配或没有数据，使用默认数据
    if (storedVersion !== CURRENT_VERSION || !stored) {
      console.log('使用默认数据，原因:', storedVersion !== CURRENT_VERSION ? '版本不匹配' : '没有存储数据');
      localStorage.setItem(VERSION_KEY, CURRENT_VERSION);
      saveWebsites(defaultWebsites);
      console.log('已保存默认数据:', defaultWebsites);
      return defaultWebsites;
    }

    const parsedData = JSON.parse(stored);
    console.log('加载的存储数据:', parsedData);
    return parsedData;
  } catch (error) {
    console.error('加载网站数据失败:', error);
    // 出错时也更新版本并返回默认数据
    localStorage.setItem(VERSION_KEY, CURRENT_VERSION);
    saveWebsites(defaultWebsites);
    return defaultWebsites;
  }
};